package com.twu.biblioteca;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.PrintStream;
import java.util.List;


public class CheckoutBookCommand {
    private final PrintStream printStream;
    private final BufferedReader bufferedReader;
    private List<LibraryBook> bookList;

    public CheckoutBookCommand(PrintStream printStream,
                               BufferedReader bufferedReader, List<LibraryBook> bookList){
        this.printStream = printStream;
        this.bufferedReader = bufferedReader;

        this.bookList = bookList;
    }

    public void checkoutBook() throws IOException {
        printStream.println("What book would you like to check out?");
        String potentialTitle = bufferedReader.readLine();
        LibraryBook potentialBook = findBook(potentialTitle);
        if (potentialBook != null && potentialBook.isAvailable()) {
            makeBookUnavailable(potentialBook);
        } else{
            printStream.println("That book is not available.");
        }
    }

    public void makeBookUnavailable(LibraryBook book) {
        book.setAvailability(false);
    }

    public LibraryBook findBook(String potentialTitle) {
        for (LibraryBook match : bookList) {
            if (potentialTitle.equals(match.toString())){
                printStream.println("Thank you! Enjoy the book.");
                return match;
            }
        }
        return null;
    }

}
